<template>
  <div class="container">
    <el-row :gutter="10" type="flex" justify="start">
      <el-col :span="1.5" class="text-align-left">
        <div id="messBox">下列服务编码还未返回预估单：{{ coding }}</div>
        <div class="color-red">
          预估单未返回时请确认以下操作是否已完成：
        </div>
        <div
          v-for="(item, index) in textArray"
          :key="index"
          class="color-red"
        >
          {{ item }}
        </div>
      </el-col>
    </el-row>
    <wz-table :columns="columns" :use-index="true" :table-data="tableData">
      <!-- 单价 -->
      <template #price="{row}">
        <div v-if="row.serviceCode">
          {{ roundingFour(row.price) }}
        </div>
      </template>
      <!--  商合预占金额(元)-->
      <template #shMoney="{row}">
        <div v-if="row.serviceCode">
          {{ rounding(row.shMoney) }}
        </div>
      </template>
      <!-- 累计验工计价数量 -->
      <template #sumNum="{row}">
        <div v-if="row.serviceCode">
          {{ roundingFour(row.sumNum) }}
        </div>
      </template>
      <!-- 累计验工金额(元) -->
      <template #sumMoney="{row}">
        <div v-if="row.serviceCode">
          {{ rounding(row.sumMoney) }}
        </div>
      </template>
      <!-- 本期验工数量 -->
      <template #currentInspectionNum="{ row }">
        <div v-if="!row.serviceCode">
          <el-input
            v-if="isCurrentInspectionNumInput(row)"
            v-model="row.currentInspectionNum"
            size="mini"
            type="text"
            placeholder=""
            @blur="handleBlur(row)"
          />
        </div>
        <div v-else @click="handleEdit(row)">
          {{ roundingFour(row.currentInspectionNum) }}
        </div>
      </template>
      <template #orderState="{ row }">
        <div>
          {{ orderStateDictionaries(row) }}
        </div>
      </template>
      <template #isPush="{ row }">
        <div>
          {{ isPushDictionaries(row) }}
        </div>
      </template>
      <template #payType="{ row }">
        <div>
          {{ payTypeDictionaries(row) }}
        </div>
      </template>
      <!-- 1:新增，2：冲销，3：查看 -->
      <template #operation="{ row }">
        <div>
          <el-button
            v-if="isAdd(row)"
            class="pms-button-primary-plain"
            @click="add(row)"
          >新增</el-button>
          <el-button
            v-if="isTrade(row)"
            class="pms-button-primary-plain"
            @click="trade(row)"
          >冲销</el-button>
          <el-button
            v-if="isDelete(row)"
            class="pms-button-primary-plain"
            @click="handleDelete(row)"
          >删除</el-button>
        </div>
      </template>
    </wz-table>
  </div>
</template>

<script>
import { INSPECTION_VALUATION_TEXT } from './enum/textEnum'
import { INSPECTION_VALUATION_DETAILS } from './enum/table'
import {
    queryinspectionValuationDetails_all,
    getServiceReceInspectionNew,
    getHaveInspection,
    updateInsValIT
} from '@/api/checkoutValuation/index'
import checkOutEnum from '@/mixins/checkOutEnum'
export default {
    name: 'InspectionValuationDetails',
    mixins: [checkOutEnum],
    data() {
        return {
            coding: [],
            textArray: [],
            columns: [],
            tableData: [],
            options: [],
            fatherNodeArr: [],
            itAccId: '',
            sign: false
        }
    },
    computed: {
        query() {
            console.log(this.$route.query)
            return this.$route.query
        },
        isAdd() {
            console.log('isAdd')
            return (row) => {
                return (
                    +this.query.queryType === 1 &&
                    +row.pid === 0 &&
                    +row.orderState === 1 &&
                    +row.ifAdd === 1
                )
            }
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewOne(row) {
            return +this.query.queryType === 2 &&
                    !row.serviceCode &&
                    row.currentInspectionNum > 0 &&
                    row.currentInspectionMoney > 0
        },
         // 2024-10-09 阻断问题if过多解决方案
         optimizeNewTwo(row) {
            return row.paymentType === 'PROGRESSING' &&
                    +row.isPush === 1 &&
                    +row.ifShowDest === 1
        },
        isTrade() {
            console.log('isTrade')
            return (row) => {
                return (
                    this.optimizeNewOne(row) && this.optimizeNewTwo(row)
                )
            }
        },
        isDelete() {
            console.log('delete')
            return (row) => {
                return row.isPush === 0 && this.getParentNode(row) === '1'
            }
        },
        isCurrentInspectionNumInput() {
            return (row) => {
                return (
                    row.isOk && !row.strVid
                )
            }
        }
    },
    mounted() {
        this.textArray = INSPECTION_VALUATION_TEXT
        this.columns = JSON.parse(JSON.stringify(INSPECTION_VALUATION_DETAILS))
        this.queryInspectionValuationDetailsAll({
            prjId: this.query.prjId
        })
        this.getServiceReceInspection({ prjId: this.query.prjId })
    },
    methods: {
        async queryInspectionValuationDetailsAll(params) {
            const { code, data } = await queryinspectionValuationDetails_all(
                params
            )
            if (+code === 200) {
                this.tableData = data || []
                for (const item of this.tableData) {
                    if (item.pid === '0') {
                        this.fatherNodeArr.push(item) // 获取所有父节点
                    }
                }
            }
        },
        async getServiceReceInspection(params) {
            const { code, data } = await getServiceReceInspectionNew(params)
            if (+code === 200 && data.length > 0) {
                data.map((v) => {
                    this.coding.push(v)
                })
                this.coding = this.coding.join(',')
            } else {
                this.coding = '无'
            }
        },
        // 获取关联父子数据得orderState
        getParentNode(e) {
            let parentVal = ''
            this.fatherNodeArr.map((fuVal) => {
                if (fuVal.vid === e.pid) {
                    parentVal = fuVal.orderState
                }
            })
            console.log(e, parentVal)
            return parentVal
        },
         // 2024-10-09 阻断问题if过多解决方案
          optimizeNewThree(row) {
            if (row.shNum - row.sumNum === 0) {
                this.$message({
                    message:
                        '当前累计验工计价数量等于商合预占数量,不支持新增操作!',
                    type: 'warning'
                })
                return true
            }
            if (row.shMoney - row.sumMoney === 0) {
                this.$message({
                    message:
                        '当前累计验工计价金额等于商合预金额,不支持新增操作!',
                    type: 'warning'
                })
                return true
            }
            return false
          },
           // 2024-10-09 阻断问题if过多解决方案
          async optimizeNewFour(row) {
            const { code, data } = await getHaveInspection({
                itAccId: this.itAccId || 30008426,
                vId: row.vid
            })
            if (+code === 200 && +data) {
                return true
            } else {
                return false
            }
          },
             // 2024-10-09 阻断问题if过多解决方案
         async optimizeNewFive(dataParams) {
            const updateInsValITRes = await updateInsValIT(dataParams)
            if (updateInsValITRes.code === '200') {
                if (updateInsValITRes.message === '操作成功') {
                    this.queryInspectionValuationDetailsAll({
                        prjId: this.query.prjId || 30000726
                    })
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        message: '新增失败',
                        type: 'error'
                    })
                }
            }
        },
         optimizeNewSix(fuZiArr, index) {
            return fuZiArr[index].projectProGress === '100' &&
                    fuZiArr[index].payType === 'PROGRESSING'
        },
        // 数组插入
        async add(row) {
            const params = {
                pId: row.vid,
                prjId: row.prjId,
                subPrjId: row.subPrjId,
                serviceCode: row.serviceCode,
                siteId: row.siteId,
                currentInspectionMoney: this.farmatMoney(
                    row.shMoney - row.sumMoney
                ),
                currentInspectionNum: row.surplusNum,
                projectProgress: '100',
                sumNum: row.shNum, // 新增累计数量直接等于商合预占数
                sumMoney: row.shMoney, // 新增累计金额直接等于商合预金额
                taxrate: row.taxrate, // 税率
                onlyBe1Flag: row.onlybe1flag,
                purchaseMode: row.purchaseMode,
                orderDetailId: row.orderDetailId
            }
            // 2024-10-09 阻断问题if过多解决方案
            if (this.optimizeNewThree(row)) {
                return
            }

            let flag = false
            flag = await this.optimizeNewFour(row)
            // const { code, data } = await getHaveInspection({
            //     itAccId: this.itAccId || 30008426,
            //     vId: row.vid
            // })
            // if (+code === 200) {
            //     if (+data) {
            //         flag = true
            //     }
            // }
            if (flag) {
                return this.$message.warning(
                    '当前验收阶段已存在未推送商合的验工计价信息，请删掉重新做验工计价！'
                )
            }
            const fuZiArr = []
            this.tableData.map((v) => {
                if (v.pid === this.fatherNodeArr[0].vid) {
                    fuZiArr.push(v)
                }
            })
            for (let index = 0; index < fuZiArr.length; index++) {
                if (this.optimizeNewSix(fuZiArr, index)) {
                    this.sign = true
                }
            }
            let inspectionTax =
                Number(params.currentInspectionMoney) * Number(params.taxrate) // 验工计价税额 = 本期验工金额*税率
            inspectionTax = this.farmatMoney(inspectionTax)
            const inspectionTaxAmount = this.farmatMoney(
                Number(params.currentInspectionMoney) + Number(inspectionTax)
            )
            const dataParams = {
                ...params,
                inspectionTax: inspectionTax,
                inspectionTaxAmount: inspectionTaxAmount,
                payType: 'PROGRESSING',
                sign: this.sign,
                flag: '1',
                itAccId: this.itAccId || 30000726
            }
            this.optimizeNewFive(dataParams)
        },
        handleBlur(row) {
            console.log(row)
        },
        handleDelete(row) {
            let parentNode = ''
            this.fatherNodeArr.map((item) => {
                if (item.vid === row.pid) {
                    parentNode = item
                }
            })
            const currentInspectionNum = row.currentInspectionNum
            const currentInspectionMoney = row.currentInspectionMoney
            const sumNum = parentNode.sumNum // 该订单累计验工数量
            const sumMoney = parentNode.sumMoney // 该订单累计验工金额
            const diffNum = Number(sumNum) - Number(currentInspectionNum)
            const diffMoney = Number(sumMoney) - Number(currentInspectionMoney)
            if (diffNum < 0) {
                // if (parentNode.onlybe1flag === 'N' && diffNum < 0) {
                this.$message({
                    message: '本订单的累计验工数量应大于等于0！',
                    type: 'warning'
                })
                return
            }
            if (diffMoney < 0) {
                // if(parentNode.ONLYBE1FLAG=="Y"&&diffMoney<0){
                this.$message({
                    message: '本订单的累计验工金额应大于等于0！',
                    type: 'warning'
                })
                return
            }
            this.$confirm('确认删除该明细？', '删除提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            }).then(async() => {
                // treegrid.loading("删除中，请稍后......")
                var ifShowDest = ''
                var strVid = ''
                if (row.strVid) {
                    ifShowDest = 1
                    strVid = row.strVid
                } else {
                    ifShowDest = 2
                }
                const onlyBe1Flag = parentNode.onlybe1flag
                const pId = row.pid
                const vId = row.vid
                const currentInspectionNums = row.currentInspectionNum
                const currentInspectionMoneys = row.currentInspectionMoney
                const serviceCode = parentNode.serviceCode
                const prjId = parentNode.prjId
                const subPrjId = parentNode.subPrjId
                const data = {
                    onlyBe1Flag: onlyBe1Flag,
                    currentInspectionNum: currentInspectionNums,
                    currentInspectionMoney: currentInspectionMoneys,
                    serviceCode: serviceCode,
                    prjId: prjId,
                    subPrjId: subPrjId,
                    pId: pId,
                    vId: vId,
                    flag: '3',
                    ifShowDest: ifShowDest,
                    strVid: strVid
                }
                const updateInsValITRes = await updateInsValIT(data)
                if (updateInsValITRes.code === '200') {
                    this.queryInspectionValuationDetailsAll({
                        prjId: this.query.prjId || 30000726
                    })
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        message: updateInsValITRes.message,
                        type: 'warning'
                    })
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.container {
    padding: 0px 20px;
}
.text-align-left {
    line-height: 25px;
    text-align: left;
}
::v-deep .el-table__fixed-right {
    height: 100% !important;
}

#messBox {
    word-break: break-all;
}
</style>
